package com.yycx.module.live.io.agora.utils;

import com.yycx.common.utils.RedisUtils;
import com.yycx.module.live.config.AgoraProperties;
import com.yycx.module.live.io.agora.rtm.RtmTokenBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@EnableConfigurationProperties(AgoraProperties.class)
public class RtmTokenBuilderUtil {

    @Autowired
    private RedisUtils redisUtils;

    private final AgoraProperties agoraProperties;

    @Autowired
    public RtmTokenBuilderUtil(AgoraProperties agoraProperties) {
        this.agoraProperties = agoraProperties;
    }

    public String getRtmToken(String userId, Integer expireTimestamp) {
        String rtmToken = "";
        try {
            String redisKey = "rtmToken:" + userId;
            if (redisUtils.hasKey(redisKey)) {
                rtmToken = redisUtils.getString(redisKey);
            } else {
                String appId = agoraProperties.getAppId();
                System.out.println("appId:" + appId);
                String certificate = agoraProperties.getCertificate();
                System.out.println("certificate:" + certificate);
                System.out.println("expireTimestamp:" + expireTimestamp);
                RtmTokenBuilder token = new RtmTokenBuilder();
                rtmToken = token.buildToken(appId, certificate, userId, RtmTokenBuilder.Role.Rtm_User, expireTimestamp);
                redisUtils.set(redisKey, rtmToken, expireTimestamp);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return rtmToken;
    }
}
